import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/NewLogin/LoginViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/GYSData.dart';
import 'package:flutter_ahj_app/base/cunchu/Constant.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/pluglin/login/LoginUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/downloadfile/sp_util.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

class YijianLogInView extends BaseStatefulWidget {
  String type;

  final String inputVC; // 从那个界面 进来 如果 从 商城 商品详情 进来 登陆之后 返回 原来界面

  YijianLogInView({this.inputVC});
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return new LoginPageState(type);
  }
}

class LoginPageState extends BaseState<LoginViewModel, YijianLogInView> {
  TextEditingController _nameContro = new TextEditingController(text: '');
  static const communicateChannel = MethodChannel('xinAnLi');
  String type;

  LoginPageState(this.type);

  bool check = true;
  String showMiMa = "1";
  String isLogIng = "0";
  String pwd = "";

  String loginType = "0"; //0：账号密码登录 1：验证码登录

  List<String> _hjName = List();
  List<String> _hjApiPath = List();
  List<String> _hjH5Path = List();
  List<DropdownMenuItem> _hjItems = new List();
  int _curHj = 0;
  bool _isCheckXY = false;
  @override
  initState() {
    super.initState();
  }

  void isShowMiMa() {
    setState(() {
      showMiMa == "1" ? showMiMa = "0" : showMiMa = "1";
    });
  }

  @override
  Widget initWidget() {
    Row avatar = new Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Image.asset(
          "img/login_logo.png",
          width: Dimens.dimens64,
          height: Dimens.dimens64,
        ),
      ],
    );
    Row avatartext = new Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          "欢迎登录青柠",
          style: new TextStyle(color: SQColor.white, fontSize: 16),
        )
      ],
    );
    Container container = new Container(
      child: new Container(
        color: SQColor.secondary1,
        alignment: Alignment.center,
        height: 48,
        child: CircularProgressIndicator(),
      ),
    );
    RaisedButton sure = new RaisedButton(
      child: new Container(
        alignment: Alignment.center,
        height: 48,
        child: new Text(
          "登录",
          style: new TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      color: SQColor.secondary1,
      disabledColor: SQColor.secondary1,
      textColor: Colors.white,
      onPressed: () {
        loginType == "0" ? _ucLogin() : _ucLogin();
      },
    );
    return new Scaffold(
      appBar: MTopBar(
          title: "用户登录",
          elevation: 0,
          rightButtonText: '游客模式',
          onRightButtonClick: () {
            Navigator.pushNamedAndRemoveUntil(
                context, "/home", (check) => false);
          }).create(),
      resizeToAvoidBottomInset: true,
      backgroundColor: SQColor.theme_color,
      body: Container(
        child: Padding(
          padding: EdgeInsets.fromLTRB(Dimens.dimens24, 0, Dimens.dimens24, 0),
          child: Column(
            children: [
              Expanded(
                child: new ListView(
                  children: <Widget>[
                    Offstage(
                      offstage:
                          HttpBaseConst.serverUrl == "https://api.xinanyun.cn/",
                      child: DropdownButton(
                        isExpanded: true,
                        items: _hjItems,
                        hint: new Text('选择环境'),
                        //当没有默认值的时候可以设置的提示
                        value: _curHj,
                        //下拉菜单选择完之后显示给用户的值
                        onChanged: (t) {
                          //下拉菜单item点击之后的回调
                          setState(() {
                            _curHj = t;
                          });
                          HttpBaseConst.baseH5Url = _hjH5Path[_curHj];
                          HttpBaseConst.serverUrl = _hjApiPath[_curHj];
                          SpUtil.putInt("curHj", _curHj);
                          ToastUtils.showToast(HttpBaseConst.serverUrl);
                        },
                        //设置阴影的高度
                        style: new TextStyle(
                            //设置文本框里面文字的样式
                            color: SQColor.black_333333),
                        iconSize: 24, //设置三角标icon的大小
                      ),
                    ),
                    new Container(
                      margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                      child: avatar,
                    ),
                    new Container(
                      margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                      child: avatartext,
                    ),
                    new Container(
                      margin: EdgeInsets.fromLTRB(
                          Dimens.dimens36, Dimens.dimens64, Dimens.dimens36, 0),
                      child: isLogIng == "0"
                          ? new RaisedButton(
                              child: new Container(
                                alignment: Alignment.center,
                                height: 48,
                                child: new Text(
                                  "本机号码一键登录",
                                  style: new TextStyle(
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                              color: SQColor.secondary1,
                              disabledColor: SQColor.secondary1,
                              textColor: Colors.white,
                              onPressed: () async {
                                if (!_isCheckXY) {
                                  return ToastUtils.showToast('请先阅读相关协议');
                                }
                                final connectivityResult =
                                    await (Connectivity().checkConnectivity());
                                if (connectivityResult ==
                                    ConnectivityResult.none) {
                                  return ToastUtils.showToast("请检查手机网络设置");
                                }

                                loginType == "0" ? _ucLogin() : _ucLogin();
                              },
                            )
                          : container,
                    ),
                    new Container(
                      margin: EdgeInsets.fromLTRB(
                          Dimens.dimens36, Dimens.dimens64, Dimens.dimens36, 0),
                      child: new RaisedButton(
                        child: new Container(
                          decoration: BoxDecoration(
                            borderRadius:
                                new BorderRadius.all(Radius.circular(3.0)),
                          ),
                          alignment: Alignment.center,
                          height: 48,
                          child: new Text(
                            "其他手机号码登录",
                            style: new TextStyle(
                              color: Colors.black,
                            ),
                          ),
                        ),
                        color: SQColor.white,
                        disabledColor: SQColor.white,
                        textColor: SQColor.black_333333,
                        onPressed: () {
                          if (!_isCheckXY) {
                            return ToastUtils.showToast('请先阅读相关协议');
                          }
                          Navigator.pushNamed(context, "/loginView");
                          // Navigator.pushNamedAndRemoveUntil(
                          //     context, "/loginView", (check) => false);
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                child: Padding(
                  padding: EdgeInsets.only(top: Dimens.dimens20),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () {
                          setState(() {
                            _isCheckXY = !_isCheckXY;
                          });
                        },
                        child: Image.asset(
                          _isCheckXY ? "img/xieyi_xz.png" : "img/xieyi_wxz.png",
                          width: Dimens.dimens20,
                          height: Dimens.dimens20,
                        ),
                      ),
                      Expanded(
                        child: RichText(
                          maxLines: 2,
                          text: TextSpan(
                            text: '  我已阅读并同意',
                            style: TextStyle(
                              color: SQColor.white,
                              fontSize: Dimens.dimens14,
                            ),
                            children: <TextSpan>[
                              TextSpan(
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Navigator.pushNamed(context, "/PTXYView",
                                        arguments: '1');
                                  },
                                text: '《平台协议》',
                                style: TextStyle(
                                    color: SQColor.secondary1,
                                    fontSize: Dimens.dimens14,
                                    fontWeight: FontWeight.bold),
                              ),
                              TextSpan(
                                text: '和',
                                style: TextStyle(
                                    color: SQColor.white,
                                    fontSize: Dimens.dimens14),
                              ),
                              TextSpan(
                                text: '《自雇者承揽协议》',
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Navigator.pushNamed(context, "/PTXYView",
                                        arguments: '2');
                                  },
                                style: TextStyle(
                                    color: SQColor.secondary1,
                                    fontSize: Dimens.dimens14,
                                    fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 50,
              ),
            ],
          ),
        ),
      ),
    );
  }

  TextEditingController _phoneController = new TextEditingController(text: ''),
      _checkController = new TextEditingController(text: '');

  @override
  void dispose() {
    super.dispose();
  }

  _checkLoginResult(Map userBeanEntity) async {
    if (userBeanEntity != null && userBeanEntity['code'] == 0) {
      UserInfoUtils.setUserToken(userBeanEntity['accessToken']);
      print(UserInfoUtils.getUserToken());

      viewModel.changeRoles();
      Stream stream = viewModel.getRoleStream();
      stream.listen((result) {
        if (result == null || result["code"] != 0) {
          UserInfoUtils.setUserToken("");
          ToastUtils.showToast("登录失败");
          isLogIng = "0";
          setState(() {});
        } else {
          saveUserData(userBeanEntity);
        }
      });
    } else if (userBeanEntity != null && userBeanEntity['code'] == 1) {
      ToastUtils.showToast(userBeanEntity['message']);
      isLogIng = "0";
      setState(() {});
    } else {
      ToastUtils.showToast("账号密码错误");
      isLogIng = "0";
      setState(() {});
    }
  }

  var encryptedString;

  _umLogin() async {
    String password = pwd;
    var encryptedString =
        await communicateChannel.invokeMethod('passwordAes', password);
    isLogIng = "1";
    setState(() {});
    viewModel.setlogInData(_nameContro.text, encryptedString);
    Stream<Map> sss = viewModel.getDataStream();
    sss.listen((userBeanEntity) {
      _checkLoginResult(userBeanEntity);
    });
  }

  _ucLogin() async {
//    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
//    if (_phoneController.text == null || _phoneController.text.trim() == "") {
//      ToastUtils.showToast("请输入手机号");
//      return;
//    }
//    bool matched = exp.hasMatch(_phoneController.text);
//    if (!matched) {
//      ToastUtils.showToast("请输入正确格式的手机号");
//      return;
//    }
//    if (_checkController.text == null || _checkController.text.trim() == "") {
//      ToastUtils.showToast("请输入验证码");
//      return;
//    }

    var data12 = await LoginUtils.YijianDengluZhibo();

    if (data12 == "-100") {
      //切换到其他方式登录
      Navigator.pushNamed(context, "/loginView");
      return;
    } else if (data12 == "1") {
      return;
    }

//  ToastUtils.showToast(data12);

    print(data12);
    isLogIng = "1";
    setState(() {});
    viewModel.checkCodeLogin("", data12);
    Stream<Map> stream = viewModel.getCheckCodeLoginStream();
    stream.listen((userBeanEntity) {
      _checkUCLoginResult(userBeanEntity);
    });
  }

  _checkUCLoginResult(Map userBeanEntity) async {
    if (userBeanEntity != null && userBeanEntity['code'] == 0) {
      UserInfoUtils.setUserToken(userBeanEntity['accessToken']);
      print(UserInfoUtils.getUserToken());

      viewModel.changeRoles();
      Stream stream = viewModel.getRoleStream();
      stream.listen((result) {
        if (result == null || result["code"] != 0) {
          UserInfoUtils.setUserToken("");
          ToastUtils.showToast("登录失败");
          isLogIng = "0";
          setState(() {});
        } else {
          saveUserData(userBeanEntity);
        }
      });
    } else if (userBeanEntity != null && userBeanEntity['code'] == 1) {
      ToastUtils.showToast(userBeanEntity['message']);
      isLogIng = "0";
      setState(() {});
    } else {
      ToastUtils.showToast("账号密码错误");
      isLogIng = "0";
      setState(() {});
    }
  }

  saveUserData(Map userBeanEntity) {
    // isLogIng = "0";
    // UserInfoUtils.setUserNiceName(userBeanEntity.realName);
    // UserInfoUtils.setUserRealName(userBeanEntity.realName);
    // UserInfoUtils.setUserName(_nameContro.text);
    // UserInfoUtils.setPassWord(encryptedString);
    // UserInfoUtils.setUserCompanyName(userBeanEntity.companyName);
    // UserInfoUtils.setUserCompanyID(userBeanEntity.tenantId);
    // UserInfoUtils.setUserAvatarName(userBeanEntity.avatar);
    // UserInfoUtils.setUserToken(userBeanEntity.accessToken);

    // print(UserInfoUtils.getUserToken());
    // UserInfoUtils.setUserId(userBeanEntity.userId.toString());
    // UserInfoUtils.setUserdeptName(userBeanEntity.deptName);
    // UserInfoUtils.setUserdeptCode(userBeanEntity.deptCode);
    // UserInfoUtils.setUserdeptIde(userBeanEntity.deptId);
    // UserInfoUtils.setSID(userBeanEntity.sid);
    // UserInfoUtils.setMID(userBeanEntity.ecId);
    // UserInfoUtils.setPW(userBeanEntity.pw);
    // viewModel.getCheckToken();
    viewModel.gysInfo();
    Stream<GYSInfo> stream = viewModel.gysInfoStream();
    stream.listen((result) {
      if (result == null) {
        viewModel.getUserRole();
        Stream<int> streamrole = viewModel.getUserRoleStream();

        streamrole.listen((event) {
          if (event == 2) {
            //风险管理师
            UserInfoUtils.setUserType(Constant.USER_RISK_MANAG);
          } else {
            UserInfoUtils.setUserType(Constant.USER_TYPE_DEDAULT);
          }
          if (widget.inputVC == '商品详情') {
            Navigator.pop(context, '刷新');
          } else {
            Navigator.pushNamedAndRemoveUntil(
                context, "/home", (check) => false);
          }
        });
      } else {
        UserInfoUtils.setUserType(Constant.USER_TYPE_GYS);
        UserInfoUtils.setGYSID("${result.supplierId}");
        UserInfoUtils.setGYSName(result.supplierName);
        UserInfoUtils.setGYSPic(result.photoUrl);
        if (widget.inputVC == '商品详情') {
          Navigator.pop(context, '刷新');
        } else {
          Navigator.pushNamedAndRemoveUntil(context, "/home", (check) => false);
        }
      }
    });
  }

  seterrorData(String errorData) {
    ToastUtils.showToast("账号密码错误");
    setState(() {
      isLogIng = "0";
    });
  }
}
